import { SubjectType } from '@/apis';
import { getAreaConfig, getIndustryConfig, getTagTypeConfig } from '@/utils/filterConfig';
import { type FilterMenuProps, ComponentType, EDatePickerTypes, type IResult } from 'vc';
import { type GreenProductCertificate, getCertificateCategory, getGreenProductTagEffective } from '../../apis';

export function useScreen() {
  const PAGE_SIZE = 15;
  const CLIENT = 'PC';

  const queryData = reactive<GreenProductCertificate>({
    pageNum: 1,
    pageSize: PAGE_SIZE,
    searchTxt: '',
    client: CLIENT
  });

  const { data: category } = useRequest(getCertificateCategory);
  const { data: tagEffective } = useRequest(getGreenProductTagEffective);

  const screen = ref<FilterMenuProps[]>([
    {
      ...getAreaConfig().value,
      submitFn: (val: IResult) => {
        const { lv1, lv2, lv3 } = val;
        queryData.provinceCode = lv1.join();
        queryData.cityCode = lv2.join();
        queryData.countryCode = lv3.join();
      }
    },
    {
      ...getIndustryConfig().value,
      submitFn: (val: IResult) => {
        const { lv1, lv2, lv3 } = val;
        queryData.industryCategoryCodeLv1 = lv1?.join() || '';
        queryData.industryCategoryCodeLv2 = lv2?.join() || '';
        queryData.industryCategoryCodeLv3 = lv3?.join() || '';
      }
    },
    {
      ...getTagTypeConfig(SubjectType.GREEN_CERTIFICATE).value,
      submitFn: (data: string) => {
        queryData.tagTypeCode = data;
      }
    },
    {
      title: '证书状态',
      component: ComponentType.MULTIPLE,
      options: tagEffective || [],
      submitFn: (data) => {
        queryData.tagEffective = data;
      }
    },
    {
      title: '产品类别',
      component: ComponentType.CASCADER,
      options: category || [],
      // checkStrictly: true,
      submitFn: (data) => {
        const { lv1, lv2 } = data;
        const newLv1: string[] = [...lv1];

        category.value.forEach((l1) => {
          const codes = lv2.filter((l2) => l2.includes(l1.code));
          if (codes.length > 0 && !lv1.includes(l1.code)) {
            newLv1.push(l1.code);
          }
        });

        let newLv2: string[] = [...lv2];
        if (lv1.length === category.value.length) {
          newLv2 = [];
        }

        queryData.categoryCodeLevel1 = newLv1.join(',');
        queryData.categoryCodeLevel2 = newLv2.join(',');
      }
    },
    {
      title: '发证日期',
      component: ComponentType.DATE,
      type: EDatePickerTypes.DATERANGE,
      shortcuts: [90, 180, 365],
      submitFn: (data: string) => {
        queryData.startDate = data[0] || '';
        queryData.endDate = data[1] || '';
      }
    }
  ]);

  return {
    PAGE_SIZE,
    queryData,
    screen
  };
}
